package com.fcl.mylibrary.http;

import android.os.Handler;
import android.os.Message;

import com.fcl.mylibrary.util.FLog;
import com.fcl.mylibrary.util.StringUtil;
import com.google.gson.Gson;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import static com.fcl.mylibrary.http.HttpUtil.getResult;

/**
 * Created by Administrator on 2017/3/20.
 */

public class HttpClient {

    private String TAG = "HttpClient";
    private String mUrl;
    private static Handler mHandler = new Handler();
    private ResultListener mResultListener;

    public HttpClient(String url, ResultListener resultListener) {
        mUrl = url;
        mResultListener = resultListener;
    }

    public void get() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(mUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestProperty("Content-type", "text/html");
                    conn.setRequestProperty("Accept-Charset", "utf-8");
                    conn.setRequestProperty("contentType", "utf-8");
                    InputStream is = conn.getInputStream();
                    final String result = getResult(is);
                    FLog.error(TAG, result);

                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mResultListener != null) {
                                mResultListener.dealResult(result);
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    public void setResultListener(ResultListener mResultListener) {
        this.mResultListener = mResultListener;
    }

    public interface ResultListener{
        void dealResult(String result);
    }

}
